// JavaScript Document
window.onload=initAll;
var usedNums=new Array(76);
function initAll(){
	//检测浏览器是否有能力理解你要使用的对象。
	if(document.getElementById){
		document.getElementById("reload").onclick=anotherCard;
		anotherCard();
	}
	else{
		alert("Sorry,your browser doesn't support this script");
	}
}

function newCard(){
	for(var i=0;i<24;i++){
		setSquare(i);
	}
}

function setSquare(thisSquare){
	var currSquare="square"+thisSquare;
	var colPlace=new Array(0,0,0,0,0,1,1,1,1,1,2,2,2,2,3,3,3,3,3,4,4,4,4,4);
	var colBasis=colPlace[thisSquare]*15;
	var newNum;
	do{
		newNum=colBasis+getNewNum()+1;
	}while(usedNums[newNum]);
	//alert(usedNums[newNum]);
	usedNums[newNum]=true;
	document.getElementById(currSquare).innerHTML=newNum;
	document.getElementById(currSquare).className="";
	document.getElementById(currSquare).onmousedown=toggleColor;
}

function getNewNum(){
	return Math.floor(Math.random()*15);
}

function anotherCard(){
	for(var i=0;i<usedNums.length;i++){
		usedNums[i]=false;
	}
	newCard();
	//返回false的原因是为了让连接不继续执行href的内容。
	return false;
}

function toggleColor(evt){
	if(evt){
		var thisSquare=evt.target;
	}
	else{
		//如果浏览器是IE，就没有evt这个参数传进来，就需要查看window对象的event属性的srcElement属性。
		var thisSquare=window.event.srcElement;
	}
	if(thisSquare.className==""){
		thisSquare.className="pickedBG";
	}
	else{
		thisSquare.className="";
	}
	checkWin();
}

function checkWin(){
	var winnningOption=-1;
	var setSquares=0;
	var currSquare;
	var winners=new Array(31,992,15360,507904,541729,557328,1083458,2162820,4329736,8519745,8659472,16252928);
	for(var i=0;i<24;i++){
		currSquare="square"+i;
		if(document.getElementById(currSquare).className!=""){
			document.getElementById(currSquare).className="pickedBG";
			setSquares=setSquares | Math.pow(2,i);
		}
	}
	winningOption=-1;
	for(var i=0;i<winners.length;i++){
		if(setSquares==winners[i]){
			winningOption=i;
			break;
		}
	}
	if(winningOption>-1){
		for(var i=0;i<24;i++){
			if(winners[winningOption]&Math.pow(2,i)){
				currSquare="square"+i;
				document.getElementById(currSquare).className="winningBG";
			}
		}
		alert("you get it!");
	}
}